/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.common.builder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;

import de.thwildau.tm.moses.internal.common.Activator;

/**
 * A handler class to execute external <code>java.lang.Process</code> instances. This class executes all Processes in 
 * a separate Thread and will return after a given Timeout. This avoids possible Deadlock's of the calling application
 * that depend on the underlying external Processes.
 *
 * @author Thomas Kistel
 * @version $Revision: 758 $
 */
public class ProcessExecutor implements IProcessExecutor {
    
    private static final int DEFAULT_PROCESS_TIMEOUT = 1000;
    
    private Lock processLock = new ReentrantLock();
    
    private ExecutorService executor = Executors.newSingleThreadExecutor();
    
    
    public ProcessExecutor() {
    }
    
    /*
     * (non-Javadoc)
     * @see IProcessExecutor#execCommand(String, IProcessExecutor.ResultHandler, IProcessExecutor.ResultType[])
     */
    @Override
    public IStatus execCommand(String command, ResultHandler resultHandler, ResultType... resultTypes) {
        return execCommand(new NullProgressMonitor(), DEFAULT_PROCESS_TIMEOUT, command, resultHandler, resultTypes);
    }
    
    /*
     * (non-Javadoc)
     * @see IProcessExecutor#execCommand(IProgressMonitor, int, String, IProcessExecutor.ResultHandler, IProcessExecutor.ResultType[])
     */
    @Override
    public IStatus execCommand(IProgressMonitor monitor, int timeout, String command, ResultHandler resultHandler, ResultType... resultStream) {
        ProcessHandler handler = new ProcessHandler(command, resultHandler, resultStream);
        Future<IStatus> future = executor.submit(handler);
        try {
            IStatus result = future.get(timeout, TimeUnit.MILLISECONDS);
            return result;
        } catch (TimeoutException e) {
            String msg = "The timeout of " + timeout + " has exceed, while waiting for the result of the external process to complete.";
            return new Status(IStatus.ERROR, Activator.getBundleId(), msg, e);
        } catch (Exception e) {
            String msg = e.getClass().getSimpleName() + " when executing Process.";
            return new Status(IStatus.ERROR, Activator.getBundleId(), msg, e);
        } finally {
            handler.destroy();
        }
    }
    
    class ProcessHandler implements Callable<IStatus> {

        private String command; 
        private ResultType[] resultStream;
        private ResultHandler resultHandler;
        private Process process;
        
        public ProcessHandler(String command, ResultHandler resultHandler, ResultType... resultStream) {
            this.command = command;
            this.resultStream = resultStream;
            this.resultHandler = resultHandler;
        }

        @Override
        public IStatus call() throws Exception {
            try {
                if(!processLock.tryLock()) {
                    String msg = "Could not execute process, because another process is currently executed.";
                    return new Status(IStatus.INFO, Activator.getBundleId(), msg);
                }
                
                try {
                    process = Runtime.getRuntime().exec(command);
                } catch(IOException e) {
                    String msg = "Executing the external Process resulted in an unexpected error.";
                    Activator.logError(msg, e);
                    return new Status(IStatus.ERROR, Activator.getBundleId(), msg, e);
                }
                
                try {
                    // process the results
                    processResults();
                    process.waitFor();
                    process.destroy();
                    return Status.OK_STATUS;
                } finally {
                    processLock.unlock();
                }
                
            } catch (IOException e) {
                String msg = "Could not read results from the subprocess.";
                Activator.logError(msg, e);
                return new Status(IStatus.ERROR, Activator.getBundleId(), msg, e);
            } 
        }
        
        public void destroy() {
            if(process != null) {
                process.destroy();
            }   
        }
        
        private void processResults() throws IOException {
            for(ResultType type : resultStream) {
                switch (type) {
                    case INPUT_STREAM:
                        processInputStream(process.getInputStream());
                        break;
                    case ERROR_STREAM:
                        processErrorStream(process.getErrorStream());
                    case NONE:
                        // call onFinished with an empty list to indicate completeness
                        resultHandler.onFinished(new ArrayList<String>());
                    default:
                }
            }
        }
        
        private void processInputStream(InputStream stream) throws IOException {
            List<String> processResultList = new ArrayList<String>();
            try(BufferedReader reader = getReader(stream)) {
                String currentLine = null;
                while ((currentLine = reader.readLine()) != null) {
                    processResultList.add(currentLine);
                    // push the single result line to the ResultHandler
                    resultHandler.onProcess(currentLine);
                }
                
                // push all read lines to the ResultHandler
                resultHandler.onFinished(processResultList);
            } 
        }
        
        private void processErrorStream(InputStream stream) throws IOException {
            List<String> processResultList = new ArrayList<String>();
            try(BufferedReader reader = getReader(stream)) {
                String currentLine = null;
                while ((currentLine = reader.readLine()) != null) {
                    processResultList.add(currentLine);
                    // push the single result line to the ResultHandler
                    resultHandler.onError(currentLine);
                }
                
                // push all read lines to the ResultHandler
                resultHandler.onFinishedWithErrors(processResultList);
            } 
        }
        
        private BufferedReader getReader(InputStream stream) {
            return new BufferedReader(new InputStreamReader(stream));
        }
    }
}
